import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { Mask } from 'antd-mobile';
import './index.less';

interface AberrantProps {
  content: string;
  duration?: number;
  onClose?: () => void;
}

const Aberrant: React.FC<AberrantProps> = ({ content, duration, onClose }) => {
  useEffect(() => {
    if (!duration) {
      return;
    }
    const timer = setTimeout(() => onClose && onClose(), duration);
    return () => clearTimeout(timer);
  }, [duration, onClose]);

  return (
    <Mask visible onMaskClick={onClose}>
      <div className="aberrant">
        <div className="aberrant__content">
          {content}
        </div>
        <div className="aberrant__line" />
        <div className="aberrant__btn" onClick={onClose}>OK</div>
      </div>
    </Mask>
  );
};

const createAberrant = (content: string, onClose?: () => void, duration?: number) => {
  if (document.getElementById('ABERRANT')) {
    return;
  }

  const div = document.createElement('div');
  div.id = 'ABERRANT';
  document.body.appendChild(div);
  const root = createRoot(div);

  const handleClose = () => {
    onClose && onClose();
    root.unmount();
    document.body.removeChild(div);
  };

  root.render(<Aberrant content={content} duration={duration} onClose={handleClose} />);
}

export default createAberrant;